<template>
  <div class="flex-column">
    <div class="flex justify-between mb-10">
      <div>
        <el-button v-if="permission.addBtn" type="primary" icon="el-icon-plus" @click="add">{{
          $t('ADD_REGION')
        }}</el-button>
        <el-button
          v-if="permission.import"
          type="primary"
          icon="el-icon-upload2"
          @click="importVisible = true"
        >{{ $t('IMPORT') }}</el-button>
      </div>
      <div class="flex-1 text-right">
        <el-input
          v-model.trim="keywords"
          style="width: 300px"
          maxlength="32"
          clearable
          :placeholder="$t('NAME_KEYWORD')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-button type="primary" class="ml-10" @click="$debounce(loadData)">{{
          $t('QUERY')
        }}</el-button>
      </div>
    </div>
    <TableView
      v-if="showTable"
      :table-header="tableHeader"
      :table-data="treeData"
      :operate-width="190"
      :options="{ pagination: false, sequence: false, expandAll: expandAll }"
      @operate="operate"
    />
    <edit
      :visible="editShow"
      :type="operateType"
      :function-name="'region'"
      :data="rowData"
      @close="close"
    />
    <ConfImportDialog
      :visible="importVisible"
      template-url="template/区域站点批量导入模板.xlsx"
      import-url="/import/importRegion"
      service-name="oen"
      import-tips="REGION_IMPORT_TIPS"
      @close="close"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import regionApi from '@/api/basebiz/RegionApi'
  import nodeApi from '@/api/oen/NodeApi'
  import { deepSearch } from '@/utils/common'
  import Edit from './Edit'
  import ConfImportDialog from '@/components/ConfImportDialog'
  import TableView from '@/components/TableView'

  export default {
    name: 'ConfRegionPage',
    components: { Edit, ConfImportDialog, TableView },
    provide() {
      return {
        functionName: 'region'
      }
    },
    data() {
      const _this = this
      return {
        importVisible: false,
        showTable: true,
        expandAll: false,
        treeData: [],
        keywords: '',
        rowData: {},
        operateType: 'add',
        editShow: false,
        tableHeader: [
          {
            label: 'NAME',
            prop: 'regionName',
            width: '250',
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'ENCODING',
            prop: 'regionId',
            width: '210',
            configType: 'extend'
          },
          {
            label: 'LONGITUDE',
            prop: 'longitude',
            width: '100'
          },
          {
            label: 'LATITUDE',
            prop: 'latitude',
            width: '100'
          },
          {
            label: 'CATEGORY',
            prop: 'regionType',
            width: '90',
            formatter(row) {
              return _this.dictMap.REGION_TYPE[row.regionType]
            }
          },
          // {
          //   label: 'SITE_TYPE',
          //   prop: 'virtualFlag',
          //   width: '90',
          //   formatter(row) {
          //     if (row.regionType !== 'STATION') {
          //       return ''
          //     }
          //     return row.virtualFlag ? _this.$t('PIPELINE_SITE') : _this.$t('NETWORK_SITE')
          //   }
          // },
          {
            label: 'STATUS',
            prop: 'status',
            width: '90',
            formatter(row) {
              return _this.dictMap.REGION_STATUS[row.status]
            }
          },
          {
            label: 'CONTACT_PERSON',
            prop: 'person',
            width: '110',
            configType: 'extend'
          },
          {
            label: 'CONTACT_NUMBER',
            prop: 'tel',
            width: '110',
            configType: 'extend'
          },
          {
            label: 'EMAIL',
            prop: 'email',
            configType: 'extend'
          },
          {
            label: 'CONTACTADDRESS',
            prop: 'address',
            configType: 'extend'
          },
          {
            label: 'DESCRIPTION',
            prop: 'description',
            width: '300'
          }
        ]
      }
    },
    computed: {
      ...mapGetters(['regionTree', 'dictMap', 'getInfo']),
      permission() {
        return this.$store.getters.getAuthData('conf:region')
      }
    },
    watch: {
      regionTree() {
        this.search(true)
      }
    },
    activated() {
      this.loadData()
    },
    methods: {
      loadData() {
        this.$store.dispatch('getRegions', { orgId: this.getInfo.org.orgId })
      },
      // 关键字搜索
      search(reload) {
        this.showTable = !!reload
        this.keywords = this.keywords.trim()
        // 根据关键字筛选树结构数据
        if (this.keywords !== '') {
          this.treeData = deepSearch(this.regionTree, 'regionName', 'children', this.keywords)
          this.expandAll = true
        } else {
          this.treeData = [...this.regionTree]
          this.expandAll = false
        }
        this.formatData(this.treeData)
        this.$nextTick(() => {
          this.showTable = true
        })
      },
      formatData(data) {
        data.forEach(i => {
          i.btns = this.getBtns(i)
          if (i.children) {
            this.formatData(i.children)
          }
        })
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'add',
            show: this.permission.addroom && row.regionType === 'STATION' && !row.virtualFlag,
            label: 'ADD_ROOM'
          },
          {
            key: 'add',
            show: this.permission.add && row.regionType === 'REGION',
            label: 'ADD_CHILD'
          },
          {
            key: 'mod',
            show: this.permission.mod,
            label: 'MOD'
          },
          {
            key: 'del',
            show: this.permission.del && !(row.children && row.children.length > 0),
            label: 'DEL'
          }
          // {
          //   key: 'moveUp',
          //   show: this.permission.mod,
          //   label: 'MOVE_UP'
          // },
          // {
          //   key: 'moveDown',
          //   show: this.permission.mod,
          //   label: 'MOVE_DOWN'
          // }
        ]
        return btns.filter(i => i.show)
      },
      // 操作
      operate(data) {
        switch (data.type) {
        case 'view':
          this.operateType = 'view'
          this.rowData = data.data
          this.editShow = true
          break
        case 'add':
          this.addChild(data.data)
          break
        case 'mod':
          this.operateType = 'mod'
          this.rowData = data.data
          this.editShow = true
          break
        case 'del':
          this.del(data.data)
          break
        case 'moveUp':
          this.move(data.data, 'up')
          break
        case 'moveDown':
          this.move(data.data, 'down')
          break
        }
      },
      // 顶部添加区域
      add() {
        this.operateType = 'add'
        this.rowData = {
          regionName: '',
          regionType: 'REGION',
          parentId: '0'
        }
        this.editShow = true
      },
      // 删除
      async del(row) {
        console.log('row', row)
        const res =
          row.regionType === 'ROOM'
            ? await nodeApi.getByRoomIds({ regionIds: row.regionId })
            : await nodeApi.getByRegionIds({ regionIds: row.regionId })
        // if(row)
        if (res && res[row.regionId]) {
          const nodeList = res[row.regionId]
          this.$message.error(
            this.$t('CANNOT_DEL_REGION', {
              type: this.$t('REGION_TYPE_' + row.regionType),
              name: row.regionName,
              nodeList: nodeList.map(i => i.nodeName).join('、')
            })
          )
        } else {
          this.$confirm(
            this.$t('CONFIRM_DELETE_THIS', {
              type: this.$t('REGION_TYPE_' + row.regionType),
              name: row.regionName
            }),
            { type: 'warning' }
          )
            .then(() => {
              regionApi
                .del(row.id, {
                  logParams: { regionName: row.regionName, regionType: row.regionType }
                })
                .then(res => {
                  if (res) {
                    this.$message.success(this.$t('DELETE_SUCCESS'))
                    this.loadData()
                  }
                })
            })
            .catch(() => {})
        }
      },
      // 添加子级
      addChild(row) {
        this.operateType = 'add'
        this.rowData = {
          regionName: '',
          regionType: 'REGION',
          virtualFlag: false,
          parentId: row.regionId,
          longitude: row.longitude,
          latitude: row.latitude
        }
        // 站点只能新增机房
        if (row.regionType === 'STATION') {
          this.rowData.regionType = 'ROOM'
        }
        if (row.regionType === 'REGION' && row.children) {
          if (row.children.some(i => i.regionType === 'STATION')) {
            this.rowData.regionType = 'STATION'
          }
          this.rowData.regionTypeDisabled = true
        }
        this.editShow = true
      },
      // 上下移动
      move(row, type) {
        if (type === 'up') {
          regionApi.up(row).then(res => {
            res && this.loadData()
          })
        } else {
          regionApi.down(row).then(res => {
            res && this.loadData()
          })
        }
      },
      // 弹窗关闭
      close(data) {
        this.editShow = false
        this.importVisible = false
        if (data.load === true || data === true) {
          this.loadData()
        }
      }
    }
  }
</script>

<style scoped></style>
